package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 去支付，生成订单
     * @author Mosetian
     * @date 2022-9-19 19:30
     * @param	orders
     * @return R
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        return orderService.submitForPay(orders);
    }

    /**
     * 分页查询订单
     * @author Mosetian
     * @date 2022-9-19 19:55
     * @param	page
     * @param	pageSize
     * @return R
     */
    @GetMapping("/userPage")
    public R userPage(Integer page, Integer pageSize){
        return orderService.pageWithAll(page, pageSize);
    }

    /**
     * 查询订单的接口
     * @author Mosetian
     * @date 2022-9-25 12:21
     * @param	page
     * @param	pageSize
     * @param	number
     * @param	beginTime
     * @param	endTime
     * @return R
     */
    @GetMapping("/page")
    public R page(int page, int pageSize, Long number, String beginTime, String endTime){
        log.info("获取到的订单信息:" + page + " " + pageSize + " " + number + " " + beginTime + " " + endTime);

        Page<Orders> ordersPage = new Page(page, pageSize);

        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.like(number != null, Orders::getNumber, number);
        //添加排序条件
        qw.orderByDesc(Orders::getCheckoutTime);
        if (beginTime != null && endTime != null) {
            qw.between(Orders::getOrderTime, beginTime, endTime);
        }

        Page<OrdersDto> ordersDtoPage = getOrdersDtoPage(ordersPage, qw);
        return R.success(ordersDtoPage);
    }
    //这是一个私有的方法,专门返回一个Page<OrdersDto>的结果
    private Page<OrdersDto> getOrdersDtoPage(Page<Orders> ordersPage, LambdaQueryWrapper<Orders> query) {
        Page<Orders> ordersPage1 = orderService.page(ordersPage, query);
        List<OrdersDto> records = ordersPage1.getRecords().stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            //地址id查姓名
            AddressBook byId = addressBookService.getById(item.getAddressBookId());
            ordersDto.setConsignee(byId.getConsignee());
            ordersDto.setUserName(byId.getConsignee());
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId, item.getNumber());
            List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        //二次复制
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        ordersDtoPage.setRecords(records);
        return ordersDtoPage;
    }

    /**
     *订单明细中新增一个Excel导出功能
     * @author Mosetian
     * @date 2022-9-25 15:53
     * @param	response
     */
    @GetMapping("/export")
    public void getExcle(HttpServletResponse response) throws IOException {
        //查询所有的订单列表
        List<Orders> list = orderService.list();
        // 响应类型,编码
        String fileName = new String("订单明细.xlsx".getBytes(), StandardCharsets.ISO_8859_1);
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 创建excel对象参数一：路径，参数二：实体类对象。sheet：表sheet名，doWrite：存放的对象集合
        EasyExcel.write(response.getOutputStream(), Orders.class).sheet("订单明细").doWrite(list);

    }
}
